﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Forms;

using AtletIS.Shared.Entities;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.Helpers
{
    public static class StartListHelper
    {

        #region Single Start List

        /// <summary>
        ///  Štartovná listina pre NErozdelenú disciplínu.
        /// </summary>
        public static void SingleStartList(DisciplineListEntity discipline)
        {
            string htmlFilePath = HtmlHelper.GetNewHtmlFileName("(Š) " + discipline.Name);
            StreamWriter sw = new StreamWriter(htmlFilePath, false, Encoding.Default);

            try
            {
                HtmlHelper.PrintHtmlHead(sw, "AtletIS");

                sw.WriteLine("<body>");

                HtmlHelper.PrintHeader(sw, "Štartovná listina / Start list", Globals.ActiveCompetition);

                sw.WriteLine("<h3>" + discipline.Name + "</h3>");
                SingleTable(discipline, sw);
                
                HtmlHelper.PrintFooter(sw);

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                sw.Close();
                sw.Dispose();

                WordHelper.CreateWordFromHtml(htmlFilePath);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        /// <summary>
        ///  Tabuľka štartovnej listiny pre NErozdelenú disciplínu.
        /// </summary>
        public static void SingleTable(DisciplineListEntity discipline, StreamWriter sw, bool isAdvance = false)
        {
            // Get performances
            DataTable dtPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(discipline.ID);

            #region Sorting

            string sSort;

            switch (discipline.DisciplineCode)
            {
                case Globals.SprintCode:
                case Globals.LongRunCode:
                    foreach (DataRow dr in dtPerformances.Rows)
                    {
                        if (Convert.ToInt32(dr["SB"]) == 0)
                            dr["SB"] = int.MaxValue;

                        if (Convert.ToInt32(dr["PB"]) == 0)
                            dr["PB"] = int.MaxValue;
                    }
                    sSort = "Lane ASC, SB DESC, PB DESC, StartNumber ASC, Surname ASC, FirstName DESC";
                    break;

                case Globals.MarathonCode:
                    sSort = "StartNumber, Surname";
                    break;

                default:
                    sSort = "Lane ASC, SB ASC, PB ASC, StartNumber ASC, Surname ASC, FirstName ASC";
                    break;
            }

            #endregion

            if (dtPerformances.Rows.Count > 0)
            {
                #region Main table

                sw.WriteLine("<table class=\"main-table\">");
                PrintTableHeaderRow(sw, discipline, isAdvance);

                int count = 1;
                foreach (DataRow dr in dtPerformances.Select(null, sSort))
                {
                    PrintHelper.PrintRowHeader(sw, count);

                    if (Convert.ToInt32(dr["Lane"]) == 0)
                        sw.WriteLine(" <td></td>");
                    else
                        sw.WriteLine("  <td align=\"center\">" + dr["Lane"].ToString() + "</td>");

                    sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintStartNumber(dr) + "</td>");
                    sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintFlagImage(dr) + "</td>");

                    // Name, Birthdate
                    if (discipline.Relay)
                    {
                        sw.Write("  <td >" + PrintHelper.PrintRelayName(dr, Globals.ActiveCompetition.ClubsCountries) + "</td>");
                    }
                    else
                    {
                        sw.WriteLine("  <td>" + PrintHelper.PrintName(dr) + "</td>");
                        sw.WriteLine("  <td align=\"center\">" + PrintHelper.PrintBirthdate(Convert.ToDateTime(dr["BirthDate"])) + "</td>");
                    }

                    // Club / Country
                    sw.WriteLine("  <td>" + PrintHelper.PrintClubCountry(Globals.ActiveCompetition.ClubsCountries, dr) + "</td>");

                    if (Convert.ToInt32(dr["SB"]) > 100 & Convert.ToInt32(dr["SB"]) != int.MaxValue)
                        sw.WriteLine("  <td align=\"center\"> " + PrintHelper.PrintResult(dr["SB"].ToString(), discipline.DisciplineCode) + "</td>");
                    else
                    {
                        sw.WriteLine("  <td align=\"center\"></td>");
                    }

                    if (Convert.ToInt32(dr["PB"]) > 100 & Convert.ToInt32(dr["PB"]) != int.MaxValue)
                        sw.WriteLine("  <td align=\"center\"> " + PrintHelper.PrintResult(dr["PB"].ToString(), discipline.DisciplineCode) + "</td>");
                    else
                    {
                        sw.WriteLine("  <td align=\"center\"></td>");
                    }

                    if (isAdvance)
                    {
                        sw.WriteLine("  <td align=\"center\"> " + PrintHelper.PrintResult(dr["AdvResult"].ToString(), discipline.DisciplineCode) + "</td>");
                    }

                    sw.WriteLine("</tr>");
                    count += 1;
                }

                sw.WriteLine("</table>");

                #endregion

                #region Discipline info table

                sw.WriteLine("<hr>");
                sw.WriteLine("<table class=\"extra\">");
                sw.WriteLine("<tr>");
                sw.WriteLine("  <td width=\"50\"></td>");
                sw.WriteLine("  <td width=\"120\"> Počet pretekárov: " + dtPerformances.Rows.Count.ToString() + "</td>");
                sw.WriteLine("  <td width=\"100\"> Čas štartu: " + discipline.StartTime.ToShortTimeString() + "</td>");
                sw.WriteLine("</tr>");
                sw.WriteLine("</table>");

                #endregion

                #region Ext. texts for discipline

                DataTable dtExtTexts = DatabaseHelper.GetExtTextsByDisciplineListIdActive(discipline.ID, "1,3");
                if (dtExtTexts.Rows.Count > 0)
                {
                    sw.WriteLine("<hr>");
                    sw.WriteLine("<table class=\"extra\">");

                    foreach (DataRow drExtText in dtExtTexts.Rows)
                    {
                        sw.WriteLine("<tr>");
                        sw.WriteLine("  <td width=\"20\"></td>");
                        sw.WriteLine("  <td>" + drExtText["Text1"] + "</td>");
                        sw.WriteLine("</tr>");
                    }

                    sw.WriteLine("</table>");
                }

                #endregion

                #region Ext. texts for performances

                if (discipline.Relay)
                {
                    ExtTextsHelper.PrintRelayTable(discipline, sw);
                }

                #endregion
            }
        }

        #endregion

        #region Multi Start List

        /// <summary>
        ///  Štartovná listina pre rozdelenú disciplínu
        /// </summary>
        public static void MultiStartList(TreeNode tnDiscipline, DisciplineListEntity discipline) // 
        {
            string htmlFilePath = HtmlHelper.GetNewHtmlFileName("(Š) " + discipline.Name);
            StreamWriter sw = new StreamWriter(htmlFilePath, false, Encoding.Default);

            try
            {
                HtmlHelper.PrintHtmlHead(sw, "AtletIS");

                sw.WriteLine("<body>");

                HtmlHelper.PrintHeader(sw, "Štartovná listina / Start list", Globals.ActiveCompetition);

                MultiTable(tnDiscipline, sw);

                HtmlHelper.PrintFooter(sw);

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                sw.Close();
                sw.Dispose();

                WordHelper.CreateWordFromHtml(htmlFilePath);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        /// <summary>
        ///  Tabuľka štartovnej listiny pre rozdelenú disciplínu.
        /// </summary>
        public static void MultiTable(TreeNode tnDiscipline, StreamWriter sw)
        {
            DisciplineListEntity headerDiscipline = DisciplineListHelper
                .ConvertToEntity(DatabaseHelper.GetDisciplineListById(Convert.ToInt32(tnDiscipline.Name)).Rows[0]);

            bool isAdvance = (headerDiscipline.SecondaryOrder > 1) ? true : false;

            DataTable dtDisciplineList = DatabaseHelper.GetDisciplineListByParentIdActive(Convert.ToInt32(tnDiscipline.Name));

            foreach (DataRow drDisciplineList in dtDisciplineList.Rows)
            {
                DisciplineListEntity discipline = DisciplineListHelper.ConvertToEntity(drDisciplineList);

                sw.WriteLine("<h3>" + tnDiscipline.Parent.Text + " - " + discipline.Name + "</h3>");
                SingleTable(discipline, sw, isAdvance);
            }
        }

        #endregion

        #region Complete Start List

        /// <summary>
        ///  Kompletná štartovná listina
        /// </summary>
        public static void CompleteStartList(TreeView tvDisciplines)
        {
            string htmlFilePath = HtmlHelper.GetNewHtmlFileName("Štartovná listina");
            StreamWriter sw = new StreamWriter(htmlFilePath, false, Encoding.Default);

            try
            {
                HtmlHelper.PrintHtmlHead(sw, "AtletIS Start List");

                sw.WriteLine("<body>");
                
                HtmlHelper.PrintHeader(sw, "Štartovná listina / Start list", Globals.ActiveCompetition);

                #region Cyklus

                foreach (TreeNode tnParent in tvDisciplines.Nodes)
                {
                    if (tnParent.Checked)
                    {
                        DataTable dtParentDiscipline = DatabaseHelper.GetDisciplineListById(Convert.ToInt32(tnParent.Name)); 
                        if (dtParentDiscipline != null && dtParentDiscipline.Rows.Count > 0)
                        {
                            DisciplineListEntity parentDiscipline = DisciplineListHelper.ConvertToEntity(dtParentDiscipline.Rows[0]);

                            DataTable dtParentPerformances = DatabaseHelper.GetPerformancesByDisciplineListId(parentDiscipline.ID);
                            if (dtParentPerformances != null && dtParentPerformances.Rows.Count > 0)
                            {
                                // NErozdelena disciplina
                                sw.WriteLine("<h3>" + parentDiscipline.Name + "</h3>");
                                StartListHelper.SingleTable(parentDiscipline, sw);
                            }
                            else
                            {
                                // Rozdelena disciplina
                                foreach (TreeNode tnChild in tnParent.Nodes)
                                {
                                    if (tnChild.Checked)
                                        StartListHelper.MultiTable(tnChild, sw);
                                }
                            }
                        }
                    }
                }

                #endregion

                HtmlHelper.PrintFooter(sw);

                sw.WriteLine("</body>");
                sw.WriteLine("</html>");

                sw.Close();
                sw.Dispose();

                WordHelper.CreateWordFromHtml(htmlFilePath);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }

                ExceptionHelper.ShowErrorInfo(ex);
            }
        }

        #endregion

        #region Private methods

        /// <summary>
        ///  Hlavička tabuľky.
        /// </summary>
        private static void PrintTableHeaderRow(StreamWriter sw, DisciplineListEntity discipline, bool isAdvance = false)
        {
            sw.WriteLine("<tr height=\"30\" bgcolor=\"#D8D8D8\">");
            sw.WriteLine("  <th width=\"30\" >#</th>");
            sw.WriteLine("  <th width=\"30\" >Št.č.</th>");
            sw.WriteLine("  <th width=\"30\"></th>");

            if (discipline.Relay)
                sw.WriteLine("  <th>Názov      </th>");
            else
            {
                sw.WriteLine("  <th>Meno   </th>");
                sw.WriteLine("  <th>Nar.</th> ");
            }

            if (Globals.ActiveCompetition.ClubsCountries == true)
                sw.WriteLine("  <th>Klub   </th>");
            else
                sw.WriteLine("  <th>Krajina   </th>");

            sw.WriteLine("  <th width=\"60\">SB</th>");
            sw.WriteLine("  <th width=\"60\">PB</th>");

            if (isAdvance)
            {
                sw.WriteLine("  <th width=\"60\">q</th>");
            }
            
            sw.WriteLine("</tr>");
        }

        #endregion

    }
}
